<template>

  <el-input v-model="smsCode" placeholder="输入验证码" prefix-icon="el-icon-chat-line-round">

    <el-popover
      slot="append"
      v-model="showSmsCaptcha"
      placement="right"
      width="400"
      trigger="click"
      @show="checkMobile"
    >
      <div style="line-height: 50px">
        <yf-captcha v-model="sendForm" />
        <el-button v-loading="loading" type="primary" @click="sendSms">发送</el-button>
      </div>
      <el-button slot="reference">
        <span v-if="left > 0">{{ left }}秒</span>
        <span v-else>发送验证码</span>
      </el-button>
    </el-popover>

  </el-input>

</template>

<script>
import { mapGetters } from 'vuex'
import YfCaptcha from '@/components/Captcha'
import { isMobile } from '@/utils/validate'
import { send } from '@/api/ability/sms'

export default {
  components: { YfCaptcha },
  props: {
    value: String,
    mobile: String
  },
  data() {
    return {
      smsCode: '',
      showSmsCaptcha: false,
      left: 0,
      timer: null,
      sendForm: {
        mobile: ''
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters([
      'siteData'
    ])
  },

  watch: {
    smsCode: {
      handler(val) {
        this.$emit('input', val)
      }
    },
    mobile: {
      handler(val) {
        this.sendForm.mobile = val
      }
    }
  },
  created() {
    this.sendForm.mobile = this.mobile
  },

  methods: {

    // 校验手机号码
    checkMobile(){
      if (this.left > 0) {
        this.showSmsCaptcha = false
        return
      }
      if (!isMobile(this.sendForm.mobile)) {
        this.$message.error('请输入有效的手机号！')
        this.showSmsCaptcha = false
        return
      }
    },

    sendSms() {
      if (this.left > 0) {
        this.showSmsCaptcha = false
        return
      }

      if (!isMobile(this.sendForm.mobile)) {
        this.$message.error('请输入有效的手机号！')
        this.showSmsCaptcha = false
        return
      }

      this.loading = true

      send(this.sendForm).then(() => {
        this.left = 60
        this.timer = setInterval(this.calc, 1000)
        this.showSmsCaptcha = false
        this.$message.success('短信发送成功，请查收手机短信！')
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    calc() {
      this.left -= 1
      if (this.left === 0) {
        clearInterval(this.timer)
      }
    }

  }
}
</script>
